﻿using DevExpress.XtraEditors;
using MesProjectWinform.Equipment.Output;
using MesProjectWinform.Equipment.Select;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesProjectWinform.Equipment.Form.ProjectMaintenance
{
    /// <summary>
    /// 项目维护添加窗体
    /// </summary>
    public partial class ProjectMaintenanceAddForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectMaintenanceAddForm()
        {
            InitializeComponent();
            // [添加] 确保事件绑定
            ValueType.SelectedIndexChanged += ValueType_SelectedIndexChanged;
        }

        /// <summary>
        /// 关闭添加窗体点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CloseButton2_Click(object sender, EventArgs e)
        {
            //关闭窗体
            this.Close();
        }

        /// <summary>
        /// 加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ProjectMaintenanceAddForm_Load(object sender, EventArgs e)
        {
            await LoadSelect();

            // [添加] 设置初始选择并触发事件
            ValueType.SelectedIndex = 0; // 默认选择"数值"
            ValueType_SelectedIndexChanged(ValueType, EventArgs.Empty);
        }

        /// <summary>
        /// 加载检验方式
        /// </summary>
        /// <returns></returns>
        private async Task LoadSelect()
        {
            List<CheckoutWayOutput> checkoutWayOutputs = new List<CheckoutWayOutput>()
            {
               new CheckoutWayOutput() { Id = 1, CheckoutWayName = "目视" },
               new CheckoutWayOutput() { Id = 2, CheckoutWayName = "擦拭" },
               new CheckoutWayOutput() { Id = 3, CheckoutWayName = "仪表测试" }
            };

            //设备数据源
            CheckoutWay.Properties.DataSource = checkoutWayOutputs;
            //设置显示的字段
            CheckoutWay.Properties.DisplayMember = "CheckoutWayName";
            //设置值字段
            CheckoutWay.Properties.ValueMember = "Id";

            //设置下拉列表的列
            CheckoutWay.Properties.Columns.Clear();
            CheckoutWay.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CheckoutWayName", "检验方式名称"));

            CheckoutWay.Properties.NullText = "请选择检验方式";

            // 设置初始值类型选择为"数值"，并触发其显示逻辑
            ValueType.SelectedIndex = 0; // 选择"数值"
            ValueType_SelectedIndexChanged(ValueType, EventArgs.Empty);

        }

        /// <summary>
        /// 点击改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValueType_SelectedIndexChanged(object sender, EventArgs e)
        {
            Console.WriteLine($"ValueType_SelectedIndexChanged 事件已触发，选中索引: {ValueType.SelectedIndex}");
            // [修改] 获取当前选择的值类型，使用SelectedIndex而不是SelectedItem
            int selectedIndex = ValueType.SelectedIndex;

            // [修改] 根据索引判断选择的值类型（0=数值，1=布尔，2=文本）
            if (selectedIndex == 0) // 数值
            {
                // 选择数值类型时，显示最小值和最大值控件
                labelControl4.Visible = true;      // 最小值标签
                ProjectMaintenanceMinNum.Visible = true;  // 最小值输入框
                labelControl5.Visible = true;      // 最大值标签
                ProjectMaintenanceMaxNum.Visible = true;  // 最大值输入框

                // 同时隐藏判断基准控件
                labelControl6.Visible = false;     // 判断基准标签
                Criterion.Visible = false;         // 判断基准输入框
            }
            else // 布尔或文本
            {
                // 隐藏最小值和最大值控件
                labelControl4.Visible = false;     // 最小值标签
                ProjectMaintenanceMinNum.Visible = false; // 最小值输入框
                labelControl5.Visible = false;     // 最大值标签
                ProjectMaintenanceMaxNum.Visible = false; // 最大值输入框

                // 显示判断基准控件
                labelControl6.Visible = true;      // 判断基准标签
                Criterion.Visible = true;          // 判断基准输入框
            }
        }

        /// <summary>
        /// 保存按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddProjectMaintenanceButton1_Click(object sender, EventArgs e)
        {
            // 项目名称非空验证
            if (string.IsNullOrWhiteSpace(ProjectMaintenanceName.Text))
            {
                XtraMessageBox.Show("项目维护名称不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ProjectMaintenanceName.Focus();
                return;
            }

            // 项目名称长度验证（假设最大长度为50个字符）
            if (ProjectMaintenanceName.Text.Length > 10)
            {
                XtraMessageBox.Show("项目维护名称不能超过10个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ProjectMaintenanceName.Focus();
                return;
            }

            // 检验方式非空验证
            if (CheckoutWay.EditValue == null)
            {
                XtraMessageBox.Show("请选择检验方式", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                CheckoutWay.Focus();
                return;
            }

            // 值类型选择验证
            if (ValueType.SelectedIndex < 0)
            {
                XtraMessageBox.Show("请选择值类型", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                ValueType.Focus();
                return;
            }

            // 根据值类型进行不同的验证
            if (ValueType.SelectedIndex == 0) // 数值类型
            {
                // 最小值非空验证
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceMinNum.Text))
                {
                    XtraMessageBox.Show("最小值不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMinNum.Focus();
                    return;
                }

                // 最小值数字验证
                if (!decimal.TryParse(ProjectMaintenanceMinNum.Text, out decimal minValue))
                {
                    XtraMessageBox.Show("最小值必须是有效的数字", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMinNum.Focus();
                    return;
                }

                // 最大值非空验证
                if (string.IsNullOrWhiteSpace(ProjectMaintenanceMaxNum.Text))
                {
                    XtraMessageBox.Show("最大值不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMaxNum.Focus();
                    return;
                }

                // 最大值数字验证
                if (!decimal.TryParse(ProjectMaintenanceMaxNum.Text, out decimal maxValue))
                {
                    XtraMessageBox.Show("最大值必须是有效的数字", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMaxNum.Focus();
                    return;
                }

                // 最大值必须大于最小值
                if (maxValue <= minValue)
                {
                    XtraMessageBox.Show("最大值必须大于最小值", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    ProjectMaintenanceMaxNum.Focus();
                    return;
                }
            }
            else // 布尔或文本类型
            {
                // 判断基准非空验证
                if (string.IsNullOrWhiteSpace(Criterion.Text))
                {
                    XtraMessageBox.Show("判断基准不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Criterion.Focus();
                    return;
                }

                // 判断基准长度验证（最多50个字符）
                if (Criterion.Text.Length > 50)
                {
                    XtraMessageBox.Show("判断基准不能超过50个字符", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Criterion.Focus();
                    return;
                }
            }

            ProjectMaintenanceOutput output = new ProjectMaintenanceOutput();
            output.ProjectMaintenanceName = ProjectMaintenanceName.Text;
            output.Criterion = Criterion.Text   ;
            if (ValueType.SelectedIndex == 0) // 数值类型
            {
                // 只有数值类型才需要转换最大值和最小值
                try
                {
                    output.ProjectMaintenanceMaxNum = Convert.ToInt32(ProjectMaintenanceMaxNum.Text);
                    output.ProjectMaintenanceMinNum = Convert.ToInt32(ProjectMaintenanceMinNum.Text);
                }
                catch (FormatException)
                {
                    XtraMessageBox.Show("最大值或最小值格式不正确，请输入有效的整数", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            else // 布尔或文本类型
            {
                // 对于布尔或文本类型，直接设置为0
                output.ProjectMaintenanceMaxNum = 0;
                output.ProjectMaintenanceMinNum = 0;
            }
            output.CheckoutWay = Convert.ToInt32(CheckoutWay.EditValue);
            // [修改] 将ValueType.SelectedIndex转换为对应的字符串值
            output.ValueType = ValueType.SelectedIndex == 0 ? "数值" :
                              (ValueType.SelectedIndex == 1 ? "布尔" : "文本");
            output.CreatedBy = "admin";
            output.CreatedTime = DateTime.Now;
            output.UpdatedBy = "admin";
            output.UpdatedTime = DateTime.Now;


            // 根据值类型设置不同的属性
            if (ValueType.SelectedIndex == 0) // 数值类型
            {
                output.ProjectMaintenanceMaxNum = Convert.ToInt32(ProjectMaintenanceMaxNum.Text);
                output.ProjectMaintenanceMinNum = Convert.ToInt32(ProjectMaintenanceMinNum.Text);
                output.Criterion = string.Empty; // 设置为空字符串，避免null
            }
            else // 布尔或文本类型
            {
                // 不需要验证最大值最小值，直接设置为0
                output.ProjectMaintenanceMaxNum = 0;
                output.ProjectMaintenanceMinNum = 0;

                // 验证判断基准
                if (string.IsNullOrWhiteSpace(Criterion.Text))
                {
                    XtraMessageBox.Show("判断基准不能为空", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    Criterion.Focus();
                    return;
                }

                output.Criterion = Criterion.Text;
            }

            try
            {
                // 调用API保存数据
                using (var client = new HttpClient())
                {
                    var json = JsonConvert.SerializeObject(output);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    // 异步调用API（这里使用同步方式简化代码）
                    var response = await client.PostAsync("http://localhost:5229/api/ProjectMaintenance/AddProjectMaintenance", content);

                    if (response.IsSuccessStatusCode)
                    {
                        XtraMessageBox.Show("添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // 设置对话框结果为OK，以便调用方知道添加成功并关闭对话框
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        XtraMessageBox.Show($"添加失败: {response.ReasonPhrase}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }


    }
}